<?php

namespace App\admin\validate;

use Respect\Validation\Validator as v;
use Respect\Validation\Exceptions\ValidationException;

class Bot extends Base
{

  public function check($data)
  {
    $data = parent::check($data);
    if ($data['backup_token']) {
      $data['backup_token'] = array_filter($data['backup_token'], function ($v) {
        return $v;
      });
    } else {
      $data['backup_token'] = [];
    }

    if ($data['backup_user_id']) {
      $data['backup_user_id'] = array_filter($data['backup_user_id'], function ($v) {
        return $v;
      });
    } else {
      $data['backup_user_id'] = [];
    }
    // compare array items count 
    $backup_validate = count($data['backup_user_id']) <=> count($data['backup_token']);
    throw_if($backup_validate < 0, ValidationException::class, '备份目标chat_id/username不能为空');
    throw_if($backup_validate > 0, ValidationException::class, '备份token不能为空');
    return $data;
  }

  protected function getRules()
  {
    return [
      'name'  =>  v::StringType()->NotEmpty()->length(1, 255)->setName('名称'),
      'token' =>  v::StringType()->NotEmpty()->length(1, 255)->setName('token'),
      'enable'   =>  v::optional(v::StringType()),
      'backup_token'  =>  v::optional(v::arrayType())->setName('备份token'),
      'backup_user_id'    =>  v::optional(v::arrayType())->setName('备份目标'),
    ];
  }
}
